import { useRef, useState } from 'react';
import { ActionType, ProColumns, ProFormInstance } from '@ant-design/pro-components';
import { MSG, msgApi } from '@/util/msg';
import { tableWidthMap } from '@/options';
import { Result } from '@/types/common/request';
import { InferObjectKeys, InferObjectValues } from '@/types/common/util';

//0新增 1修改 2详情 3删除
const formDataMap = {
  '0': 'insert',
  '1': 'update',
  '2': 'detail',
  '3': 'delete',
} as const;

type FormType = InferObjectKeys<typeof formDataMap>;
type DataType = InferObjectValues<typeof formDataMap>;

interface PropsType {
  call: () => Promise<Result | void>;
  messageTitle?: (typeof defaultMessage)['update'];
  messageType?: DataType;
}

const formTitle = [MSG.INSERT_TITLE, MSG.UPDATE_TITLE, MSG.DETAIL_TITLE];
const defaultMessage: {
  [k in Exclude<DataType, 'detail'>]: {
    success: string;
    loading: string;
    error: string;
  };
} = {
  update: {
    success: MSG.UPDATE_SUCCESS,
    loading: MSG.UPDATE_LOADING,
    error: MSG.UPDATE_ERROR,
  },
  insert: {
    success: MSG.INSERT_SUCCESS,
    loading: MSG.INSERT_LOADING,
    error: MSG.INSERT_ERROR,
  },
  delete: {
    success: MSG.DELETE_SUCCESS,
    loading: MSG.DELETE_LOADING,
    error: MSG.DELETE_ERROR,
  },
};
// const initNoIgnoreColumn = [
//   'index',
//   'seq',
//   'createTime',
//   'updateTime',
//   'operationId',
//   'target',
//   'option',
//   'mobile',
//   'avatar',
//   'iconName',
//   'isShow',
// ] as const;

//有地方只需要使用此方法，所以单独提出 (roleForm)
export const finishMsg = async ({ messageType = 'update', call, messageTitle }: PropsType) => {
  if (messageType === 'detail') return;
  const loading = msgApi.loading((messageTitle || defaultMessage[messageType])['loading']);
  try {
    const ret = await call();
    if (ret && !ret?.success) {
      msgApi.error(ret?.message || (messageTitle || defaultMessage[messageType])['error']);
      return;
    }
    msgApi.success((messageTitle || defaultMessage[messageType])['success']);
  } catch (e) {
    console.log(e);
  } finally {
    loading();
  }
};

const usePageVariable = <DataType>(columns?: ProColumns<DataType>[]) => {
  const [formModel, setFormModel] = useState<boolean>(false);
  const [formType, setFormType] = useState<FormType>('0'); //0新增 1修改 2详情
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [currentRow, setCurrentRow] = useState<DataType>();
  const [delMsgOpen, setDelMsgOpen] = useState<boolean>(false);
  const changeForm = (item?: DataType, type: FormType = '0') => {
    setCurrentRow(item || undefined);
    setFormType(type);
    if (type === '3') {
      setDelMsgOpen(true);
      return;
    }
    setFormModel(true);
  };
  const getFormTitle = () => formTitle[formType];
  const newColumns = (
    columns?.map((c) => {
      if (c.valueType === 'option') {
        c.key = c.valueType;
        // @ts-ignore
        const width = c?.render().filter((c) => c !== false).length * 80;
        if (width > 0) c.width = width;
        c.fixed = 'right';
      } else {
        // 自动分配宽度 width: 0
        if (typeof c.title === 'string' && c.width === undefined && (!c.hidden || !c.hideInTable)) {
          // @ts-ignore
          if (tableWidthMap[c.dataIndex]) {
            // if (tableWidthMap[c.dataIndex] && initNoIgnoreColumn.some((v) => v === c.dataIndex)) {
            // @ts-ignore
            c.width = tableWidthMap[c.dataIndex];
          }
        }

        //将width为0的列设置为undefined
        // c.width = c.width || undefined;
        c.ellipsis = c.ellipsis !== false; // ProScrollTable的 x: 'max-content' 二选一
      }
      // c.render = c.render || function (dom, record) {
      //   return dom
      // };
      return c;
    }) || []
  ).filter((c) => !(c.valueType === 'option' && !c.width));
  // console.log('=================', columns);
  const getMessageType = (formType: FormType) => {
    return formDataMap[formType];
  };

  const newFinishMsg = async (
    call: PropsType['call'],
    props?: Omit<PropsType, 'call' | 'messageType'>,
  ) => {
    await finishMsg({
      ...props,
      messageType: getMessageType(formType),
      call,
    });
  };
  return {
    formModel,
    setFormModel,
    formType,
    actionRef,
    formRef,
    currentRow,
    setCurrentRow,
    finishMsg: newFinishMsg,
    columns: newColumns,
    changeForm,
    getFormTitle,
    setFormType,
    delMsgOpen,
    setDelMsgOpen,
  };
};
export default usePageVariable;
